package com.ruoyi.settled.service;

import com.github.wxpay.sdk.WXPay;
import com.ruoyi.settled.domain.WechatPayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatPayService {

    private final WechatPayConfig wechatPayConfig;

    @Autowired
    public WechatPayService(WechatPayConfig wechatPayConfig) {
        this.wechatPayConfig = wechatPayConfig;
    }

    public String createPayment(String outTradeNo, String totalAmount, String body) {
        try {
            WXPay wxpay = new WXPay(wechatPayConfig);

            Map<String, String> data = new HashMap<>();
            data.put("body", body);
            data.put("out_trade_no", outTradeNo);
            data.put("total_fee", totalAmount);
            data.put("spbill_create_ip", "127.0.0.1");
            data.put("notify_url", wechatPayConfig.getNotifyUrl());
            data.put("trade_type", wechatPayConfig.getTradeType());

            Map<String, String> response = wxpay.unifiedOrder(data);
            if ("SUCCESS".equals(response.get("return_code"))) {
                return response.get("code_url"); // 返回支付二维码链接
            } else {
                throw new RuntimeException("微信支付请求失败: " + response.get("return_msg"));
            }
        } catch (Exception e) {
            throw new RuntimeException("微信支付请求异常", e);
        }
    }
}